<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/super/favicon.ico" />
    <title>添加/编辑科普文章 - 见闻间管理后台</title>
    <link rel="stylesheet" href="/super/assets/index-a23242ca.css">
    <!-- TinyMCE富文本编辑器 -->
    <script src="/super/tinymce/tinymce/js/tinymce/tinymce.min.js"></script>
    <style>
        /* 基础页面样式 */
        body {
            background-color: #121212;
            color: #ffffff;
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
        }

        .app-loading {
            position: absolute;
            top: 0px;
            left: 0px;
            right: 0px;
            bottom: 0px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            background: #212121;
        }

        .app-loading__loader {
            position: relative;
        }

        .loading__logo {
            position: absolute;
            z-index: 1;
            inset: 10px;
            width: 44px;
            height: 44px;
            border-radius: 50%;
        }

        .loading__loader {
            width: 64px;
            height: 64px;
            border-radius: 50%;
            border: 3px solid rgba(255, 255, 255, 0.1);
            border-left-color: #4CAF50;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .science-container {
            padding: 20px;
        }

        .science-container h1 {
            color: #ffffff;
            margin-bottom: 20px;
        }

        /* 表单样式 */
        .form-container {
            background-color: #1e1e1e;
            padding: 25px;
            border-radius: 8px;
            max-width: none;
            width: 95%;
            margin: 0 auto;
        }
        
        .science-container {
            padding: 20px;
            max-width: none;
            width: 98%;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            color: #cccccc;
            font-size: 14px;
            margin-bottom: 8px;
        }

        .form-input {
            width: 100%;
            padding: 10px 12px;
            background-color: #2d2d2d;
            border: 1px solid #444;
            border-radius: 4px;
            color: #ffffff;
            font-size: 14px;
            box-sizing: border-box;
        }

        .form-textarea {
            width: 100%;
            padding: 10px 12px;
            background-color: #2d2d2d;
            border: 1px solid #444;
            border-radius: 4px;
            color: #ffffff;
            font-size: 14px;
            min-height: 300px;
            resize: vertical;
            box-sizing: border-box;
        }

        .form-select {
            width: 100%;
            padding: 10px 12px;
            background-color: #2d2d2d;
            border: 1px solid #444;
            border-radius: 4px;
            color: #ffffff;
            font-size: 14px;
            box-sizing: border-box;
        }

        /* 按钮样式 */
        .form-actions {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #45a049;
        }

        .btn-secondary {
            background-color: #555;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #666;
        }

        /* 图片上传预览 */
        .image-preview {
            margin-top: 10px;
            max-width: 200px;
            max-height: 200px;
            display: none;
        }

        .image-preview.show {
            display: block;
        }
    </style>
</head>

<body>
    <div id="loading" class="app-loading">
        <div class="app-loading__loader">
            <div class="loading__loader"></div>
        </div>
    </div>

    <div class="science-container" style="display: none;">
        <h1 id="page-title">添加科普文章</h1>
        
        <div class="form-container">
            <form id="science-form">
                <!-- 隐藏的ID字段，用于编辑模式 -->
                <input type="hidden" id="article-id" name="id">
                
                <div class="form-group">
                    <label for="title">文章标题 <span style="color: #ff4444;">*</span></label>
                    <input type="text" id="title" name="title" class="form-input" placeholder="请输入文章标题" required>
                </div>
                
                <div class="form-group">
                    <label for="user_name">用户</label>
                    <div style="display: flex; gap: 10px;">
                        <input type="hidden" id="user_id" name="user_id">
                        <input type="text" id="user_name" class="form-input" placeholder="请输入用户名或手机号搜索" style="flex: 1;">
                        <button type="button" id="searchUserBtn" class="btn btn-secondary">搜索用户</button>
                    </div>
                    <div id="userListDropdown" style="margin-top: 5px; max-height: 200px; overflow-y: auto; background: #2d2d2d; border: 1px solid #444; border-radius: 4px; display: none;">
                        <!-- 用户列表将通过JavaScript动态加载 -->
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="category_id">文章分类 <span style="color: #ff4444;">*</span></label>
                    <select id="category_id" name="category_id" class="form-select" required>
                        <option value="">请选择分类</option>
                        <!-- 分类选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="content">文章内容 <span style="color: #ff4444;">*</span></label>
                    <textarea id="content" name="content" class="form-textarea" placeholder="请输入文章内容"></textarea>
                </div>
                
                <div class="form-group">
                    <label for="source">文章来源</label>
                    <input type="text" id="source" name="source" class="form-input" placeholder="请输入文章来源">
                </div>
                
                <div class="form-group">
                    <label for="cover_image">封面图片</label>
                    <div style="display: flex; gap: 10px; margin-bottom: 10px;">
                        <input type="text" id="cover_image" name="cover_image" class="form-input" placeholder="请输入封面图片URL" style="flex: 1;">
                        <input type="file" id="cover_file" accept="image/*" style="display: none;">
                        <button type="button" id="upload-btn" class="btn btn-secondary">选择图片</button>
                    </div>
                    <img id="cover-preview" class="image-preview" src="" alt="封面预览">
                    <div id="upload-progress" style="margin-top: 10px; display: none;">
                        <div style="color: #4CAF50; font-size: 14px;">上传中...</div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="views">浏览量</label>
                    <input type="number" id="views" name="views" class="form-input" placeholder="请输入浏览量" value="0" min="0">
                </div>
                
                <div class="form-group">
                    <label for="likes">点赞数</label>
                    <input type="number" id="likes" name="likes" class="form-input" placeholder="请输入点赞数" value="0" min="0">
                </div>
                
                <div class="form-group">
                    <label for="publish_time">发布时间</label>
                    <input type="datetime-local" id="publish_time" name="publish_time" class="form-input">
                </div>
                
                <div class="form-group">
                    <label for="disclaimer">免责声明</label>
                    <textarea id="disclaimer" name="disclaimer" class="form-textarea" placeholder="请输入免责声明"></textarea>
                </div>
                
                <div class="form-group">
                    <label for="status">状态</label>
                    <select id="status" name="status" class="form-select">
                        <option value="1">正常</option>
                        <option value="2">隐藏</option>
                    </select>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <button type="button" id="cancel-btn" class="btn btn-secondary">取消</button>
                 </div>
            </form>
        </div>
    </div>

    <script>
        // 初始化TinyMCE富文本编辑器
        function initTinyMCE() {
            if (typeof tinymce !== 'undefined') {
                tinymce.init({
                    selector: '#content',
                    language: 'zh_CN',
                    language_url: '/super/tinymce/langs/zh_CN.js',
                    height: 400,
                    menubar: true,
                    plugins: [
                        'advlist autolink lists link image charmap print preview anchor',
                        'searchreplace visualblocks code fullscreen',
                        'insertdatetime media table paste code help wordcount'
                    ],
                    toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
                    content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 14px; color: #333; background-color: #fff; }',
                    setup: function(editor) {
                        console.log('TinyMCE编辑器初始化完成');
                        editor.on('init', function() {
                            console.log('编辑器已准备就绪，可以设置内容');
                        });
                    },
                    init_instance_callback: function(editor) {
                        console.log('编辑器实例回调：', editor.id);
                        // 确保表单提交时能够获取内容
                        document.getElementById('science-form').addEventListener('submit', function(e) {
                            if (editor && editor.getContent) {
                                console.log('通过回调确保内容被保存');
                                const textarea = document.getElementById(editor.id);
                                if (textarea) {
                                    textarea.value = editor.getContent();
                                }
                            }
                        });
                    }
                });
            }
        }

        // 获取编辑器内容
        function getEditorContent() {
            console.log('尝试获取编辑器内容');
            if (typeof tinymce !== 'undefined') {
                console.log('tinymce已加载');
                if (tinymce.get('content')) {
                    console.log('找到编辑器实例，获取内容');
                    const content = tinymce.get('content').getContent();
                    console.log('获取的内容:', content);
                    return content;
                } else {
                    console.log('编辑器实例未准备好，回退到textarea');
                }
            } else {
                console.log('tinymce未加载，回退到textarea');
            }
            const textareaContent = document.getElementById('content').value;
            console.log('获取的textarea内容:', textareaContent);
            return textareaContent;
        }

        // 设置编辑器内容
        function setEditorContent(content) {
            console.log('尝试设置编辑器内容:', content);
            if (typeof tinymce !== 'undefined') {
                console.log('tinymce已加载');
                if (tinymce.get('content')) {
                    console.log('找到编辑器实例，设置内容');
                    tinymce.get('content').setContent(content);
                } else {
                    console.log('编辑器实例未准备好，等待...');
                    // 延迟重试设置内容
                    setTimeout(function() {
                        if (tinymce.get('content')) {
                            console.log('延迟后设置内容');
                            tinymce.get('content').setContent(content);
                        } else {
                            console.log('编辑器仍未准备好，回退到textarea');
                            document.getElementById('content').value = content;
                        }
                    }, 500);
                }
            } else {
                console.log('tinymce未加载，回退到textarea');
                document.getElementById('content').value = content;
            }
        }

        // 显示加载中
        function showLoading() {
            const loadingElement = document.getElementById('loading');
            const containerElement = document.querySelector('.science-container');
            
            if (loadingElement) {
                loadingElement.style.display = 'flex';
            }
            
            if (containerElement) {
                containerElement.style.display = 'none';
            }
        }

        // 隐藏加载中
        function hideLoading() {
            const loadingElement = document.getElementById('loading');
            const containerElement = document.querySelector('.science-container');
            
            if (loadingElement) {
                loadingElement.style.display = 'none';
            }
            
            if (containerElement) {
                containerElement.style.display = 'block';
            }
        }

        // 获取URL参数
        function getUrlParams() {
            const params = {};
            const queryString = window.location.search.slice(1);
            const pairs = queryString.split('&');
            
            for (const pair of pairs) {
                const [key, value] = pair.split('=');
                if (key) {
                    params[decodeURIComponent(key)] = decodeURIComponent(value || '');
                }
            }
            
            return params;
        }

        // 获取分类数据
        async function fetchCategories() {
            try {
                const url = new URL('/science/api/categories', window.location.origin);
                const response = await fetch(url);
                const data = await response.json();
                
                if ((data.code === 200 || data.code === 0) && data.data) {
                    const categorySelect = document.getElementById('category_id');
                    if (categorySelect) {
                        // 清空现有选项（保留第一个）
                        while (categorySelect.options.length > 1) {
                            categorySelect.remove(1);
                        }
                        
                        // 添加分类选项
                        data.data.forEach(category => {
                            const option = document.createElement('option');
                            option.value = category.id;
                            option.textContent = category.name;
                            categorySelect.appendChild(option);
                        });
                    }
                }
            } catch (error) {
                console.error('获取分类列表失败:', error);
            }
        }

        // 获取文章详情数据（编辑模式）
        async function fetchArticleDetail(id) {
            try {
                showLoading();
                
                console.log('fetchArticleDetail被调用，文章ID:', id);
                
                const url = new URL(`/science/api/detail?id=${id}`, window.location.origin);
                const response = await fetch(url);
                const data = await response.json();
                
                console.log('fetchArticleDetail API响应:', data);
                
                if ((data.code === 200 || data.code === 0) && data.data) {
                    const article = data.data;
                    
                    console.log('获取到的文章数据:', article);
                    console.log('获取到的用户ID:', article.user_id);
                    
                    // 填充表单数据
                    document.getElementById('article-id').value = article.id || '';
                    document.getElementById('title').value = article.title || '';
                    document.getElementById('user_id').value = article.user_id || '';
                    console.log('设置到userId输入框的值:', article.user_id);
                    setEditorContent(article.content || '');
                    document.getElementById('source').value = article.source || '';
                    document.getElementById('category_id').value = article.category_id || '';
                    document.getElementById('cover_image').value = article.cover_image || '';
                    document.getElementById('views').value = article.views || 0;
                    document.getElementById('likes').value = article.likes || 0;
                    document.getElementById('status').value = article.status || 1;
                    document.getElementById('content').value = article.content || '';
                    // 处理发布时间
                    if (article.publish_time) {
                        const publishTime = new Date(parseInt(article.publish_time) * 1000);
                        document.getElementById('publish_time').value = publishTime.toISOString().slice(0, 16);
                    }
                    
                    // 处理免责声明
                    document.getElementById('disclaimer').value = article.disclaimer || '';
                    
                    // 更新页面标题
                    document.getElementById('page-title').textContent = '编辑科普文章';
                    // 确保用户数据加载完成
                    await loadUserData(article.user_id);
                    // 显示封面预览
                    updateCoverPreview();
                }
            } catch (error) {
                console.error('获取文章详情失败:', error);
                alert('获取文章详情失败，请重试');
            } finally {
                hideLoading();
            }
        }

        // 更新封面预览
        function updateCoverPreview() {
            const coverImageInput = document.getElementById('cover_image');
            const coverPreview = document.getElementById('cover-preview');
            
            if (coverImageInput && coverPreview) {
                const imageUrl = coverImageInput.value.trim();
                
                if (imageUrl) {
                    coverPreview.src = imageUrl;
                    coverPreview.classList.add('show');
                } else {
                    coverPreview.classList.remove('show');
                }
            }
        }

        // 上传图片
        async function uploadImage(file) {
            try {
                const uploadProgress = document.getElementById('upload-progress');
                if (uploadProgress) {
                    uploadProgress.style.display = 'block';
                }

                // 创建FormData对象
                const formData = new FormData();
                formData.append('file', file);
                formData.append('group_id', 0); // 默认分组ID

                // 构建上传URL - 根据项目路由模式修改
                const uploadUrl = new URL('/file/image', window.location.origin);

                // 发送上传请求
                const response = await fetch(uploadUrl, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                // 检查上传结果
                if (data.code === 200 || data.code === 0) {
                    // 上传成功，设置图片URL
                    document.getElementById('cover_image').value = data.data.url;
                    updateCoverPreview();
                } else {
                    alert('上传失败：' + (data.msg || '未知错误'));
                }
            } catch (error) {
                console.error('上传图片失败:', error);
                alert('上传失败，请重试');
            } finally {
                const uploadProgress = document.getElementById('upload-progress');
                if (uploadProgress) {
                    uploadProgress.style.display = 'none';
                }
            }
        }

        // 提交表单数据
        async function submitForm(e) {
            e.preventDefault();
            
            try {
                showLoading();
                
                // 手动验证必填字段
                const title = document.getElementById('title').value.trim();
                const categoryId = document.getElementById('category_id').value;
                const content = getEditorContent().trim();
                
                if (!title) {
                    alert('请输入文章标题');
                    hideLoading();
                    return;
                }
                
                if (!categoryId) {
                    alert('请选择文章分类');
                    hideLoading();
                    return;
                }
                
                if (!content) {
                    alert('请输入文章内容');
                    hideLoading();
                    return;
                }
                
                // 确保编辑器内容同步到textarea
                if (typeof tinymce !== 'undefined' && tinymce.get('content')) {
                    document.getElementById('content').value = content;
                }
                
                // 获取表单数据
                const formData = new FormData(document.getElementById('science-form'));
                const articleId = formData.get('id');
                
                // 构建请求数据
                const requestData = {};
                formData.forEach((value, key) => {
                    if (key !== 'id') {
                        if (key === 'content') {
                            // 对于内容字段，使用富文本编辑器的内容
                            requestData[key] = content;
                        } else {
                            requestData[key] = value;
                        }
                    }
                });
                
                // 处理发布时间
                if (requestData.publish_time) {
                    requestData.publish_time = Math.floor(new Date(requestData.publish_time).getTime() / 1000);
                }
                
                console.log('提交的表单数据:', requestData);
                
                // 构建URL和设置请求方法
                let url, method;
                if (articleId) {
                    url = new URL(`/science/api/update?id=${articleId}`, window.location.origin);
                    method = 'POST';
                } else {
                    url = new URL('/science/api/create', window.location.origin);
                    method = 'POST';
                }
                
                // 发送请求
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });
                
                const data = await response.json();
                
                if ((data.code === 200 || data.code === 0) && data.msg) {
                    alert(data.msg);
                    // 跳转回列表页
                    // window.location.href = new URL('/science/list/index', window.location.origin).href;
                      window.location.href = new URL('/super#/science/list/index', window.location.origin).href;
                    // http://localhost:11013/super#/science/list/index
                } else {
                    alert('保存失败：' + (data.msg || '未知错误'));
                }
            } catch (error) {
                console.error('保存文章失败:', error);
                alert('保存失败，请重试');
            } finally {
                hideLoading();
            }
        }

        // 初始化页面
        async function init() {
            try {
                showLoading();
                
                // 获取URL参数
                const params = getUrlParams();
                const articleId = params.id;
                
                // 初始化富文本编辑器
                initTinyMCE();
                
                // 加载分类数据
                await fetchCategories();
                
                // 初始化用户选择功能
                initUserSelect();
                
                // 无论是否有用户ID，都尝试调用一次loadUserData函数，用于测试接口
            console.log('=== 测试调用loadUserData函数 ===');
            // loadUserData('3'); // 硬编码用户ID 9 用于测试
                
                // 如果有ID参数，加载文章详情（编辑模式）
                if (articleId) {
                    await fetchArticleDetail(articleId);
                } else {
                    // 添加模式，设置默认发布时间为当前时间
                    const now = new Date();
                    document.getElementById('publish_time').value = now.toISOString().slice(0, 16);
                }
                
                // 最后隐藏加载状态
                hideLoading();
                
                // 绑定封面预览更新事件
                document.getElementById('cover_image').addEventListener('input', updateCoverPreview);

                // 绑定文件上传事件
                document.getElementById('upload-btn').addEventListener('click', () => {
                    document.getElementById('cover_file').click();
                });

                document.getElementById('cover_file').addEventListener('change', (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        uploadImage(file);
                    }
                });
                
                // 绑定表单提交事件
                document.getElementById('science-form').addEventListener('submit', submitForm);
                
                // 绑定取消按钮事件
                document.getElementById('cancel-btn').addEventListener('click', () => {
                    window.location.href = new URL('/science/list/index', window.location.origin).href;
                });
            } catch (error) {
                console.error('页面初始化失败:', error);
                hideLoading();
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
        
        // 定义全局变量，让loadUserData可以访问
        let userInputGlobal;
        let userIdInputGlobal;
        
        // 初始化用户选择功能
        function initUserSelect() {
            const searchBtn = document.getElementById('searchUserBtn');
            userInputGlobal = document.getElementById('user_name');
            userIdInputGlobal = document.getElementById('user_id');
            const userDropdown = document.getElementById('userListDropdown');
            const formGroup = userInputGlobal.closest('.form-group');
            
            // 添加调试信息
            console.log('用户选择功能初始化:', {
                searchBtn: !!searchBtn,
                userInputGlobal: !!userInputGlobal,
                userIdInputGlobal: !!userIdInputGlobal,
                userDropdown: !!userDropdown,
                formGroup: !!formGroup
            });
            
            if (userDropdown) {
                console.log('下拉框初始状态:', userDropdown.style.display);
            }
            
            // 搜索用户函数
            async function searchUsers() {
                await loadUserList();
                userDropdown.style.display = 'block';
                
                // 调整下拉框位置
                const rect = formGroup.getBoundingClientRect();
                userDropdown.style.position = 'absolute';
                userDropdown.style.left = rect.left + 'px';
                userDropdown.style.top = (rect.bottom + window.scrollY) + 'px';
                userDropdown.style.width = rect.width + 'px';
                userDropdown.style.zIndex = '1000';
            }
            
            // 点击搜索按钮显示用户列表
            searchBtn.addEventListener('click', searchUsers);
            
            // 输入框按Enter键搜索
            if (userInputGlobal) {
                userInputGlobal.addEventListener('keypress', function(event) {
                    if (event.key === 'Enter') {
                        event.preventDefault(); // 防止表单提交
                        searchUsers();
                    }
                });
            }
            
            // 加载用户列表
            async function loadUserList() {
                try {
                    if (!userInputGlobal) {
                        console.error('用户输入框未找到');
                        return;
                    }
                    
                    const searchText = userInputGlobal.value.trim();
                    console.log('搜索文本:', searchText);
                    
                    // 模拟一些用户数据用于测试
                    const mockUsers = [
                        {id: 1, name: '张三'},
                        {id: 2, name: '李四'},
                        {id: 3, name: '王五'}
                    ];
                    
                    // 从localStorage获取JWT token
                    const token = localStorage.getItem('token') || '';
                    console.log('搜索用户使用的认证令牌:', token);
                    
                    // 添加认证头部的fetch请求
                    const response = await fetch(`/user/api/select?name=${encodeURIComponent(searchText)}`, {
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Content-Type': 'application/json'
                        }
                    });
                    const result = await response.json();
                    // const result = {code: 200, data: mockUsers};
                
                    // 添加调试日志
                    console.log('API响应数据:', result);
                    
                    // 确保result.data是数组
                    const userData = Array.isArray(result.data) ? result.data : [];
                    
                    console.log('转换后的数据:', userData);
                    
                    if (result.code === 200 && userData.length > 0) {
                        let filteredUsers = userData;
                        
                        // 如果有搜索文本，过滤用户（支持按名称搜索）
                        if (searchText) {
                            filteredUsers = userData.filter(user => 
                                user && user.name && user.name.toLowerCase().includes(searchText.toLowerCase())
                            );
                        }
                        
                        // 清空并填充用户列表
                        userDropdown.innerHTML = '';
                        console.log('过滤后的用户数据:', filteredUsers);
                        if (filteredUsers.length === 0) {
                            userDropdown.innerHTML = '<div style="padding: 10px; color: #999; text-align: center;">未找到用户</div>';
                        } else {
                            filteredUsers.forEach(user => {
                                const userItem = document.createElement('div');
                                userItem.style.padding = '10px';
                                userItem.style.cursor = 'pointer';
                                userItem.style.borderBottom = '1px solid #444';
                                userItem.innerHTML = `ID: ${user.id} - ${user.name}`;
                                
                                // 鼠标悬停效果
                                userItem.addEventListener('mouseenter', function() {
                                    this.style.backgroundColor = '#3a3a3a';
                                });
                                userItem.addEventListener('mouseleave', function() {
                                    this.style.backgroundColor = 'transparent';
                                });
                                
                                // 点击选择用户
                    userItem.addEventListener('click', function() {
                        if (userIdInputGlobal) {
                            userIdInputGlobal.value = user.id;
                        }
                        if (userInputGlobal) {
                            userInputGlobal.value = user.name;
                        }
                        userDropdown.style.display = 'none';
                    });
                                
                                userDropdown.appendChild(userItem);
                            });
                        }
                    } else {
                        userDropdown.innerHTML = '<div style="padding: 10px; color: #999; text-align: center;">暂无用户数据</div>';
                    }
                } catch (error) {
                    console.error('加载用户列表失败:', error);
                    userDropdown.innerHTML = '<div style="padding: 10px; color: #ff6b6b; text-align: center;">加载失败，请重试</div>';
                }
            }
            
            // 点击页面其他地方隐藏下拉框
            document.addEventListener('click', function(event) {
                if (!formGroup.contains(event.target) && event.target !== searchBtn) {
                    userDropdown.style.display = 'none';
                }
            });
            
            // 编辑模式下，如果有用户ID，加载用户信息
            console.log('检查用户ID是否存在:', {
                userIdInputGlobal: !!userIdInputGlobal,
                userIdValue: userIdInputGlobal ? userIdInputGlobal.value : 'undefined',
                shouldLoadUserData: userIdInputGlobal && userIdInputGlobal.value && userIdInputGlobal.value !== '0',
                // 获取URL参数进行对比
                urlArticleId: new URLSearchParams(window.location.search).get('id')
            });
            
            // 检查是否在编辑模式下（有文章ID）
            const urlArticleId = new URLSearchParams(window.location.search).get('id');
            
            // 修改条件：只要userIdInputGlobal存在且有文章ID（编辑模式），就尝试加载用户数据
            if (userIdInputGlobal && urlArticleId) {
                const userId = userIdInputGlobal.value || '';
                console.log('进入编辑模式（文章ID:', urlArticleId, '），尝试加载用户ID为', userId, '的信息');
                
                // 无论userId是否为空或为0，都调用loadUserData
                // loadUserData(userId);
            } else {
                console.log('未进入编辑模式或用户输入框未初始化');
            }
        }
        
        // 添加一个计数器来跟踪loadUserData被调用的次数
        let loadUserDataCallCount = 0;
        
        // 加载指定ID的用户数据
        async function loadUserData(userId) {
            console.log('=== loadUserData函数被调用 ===');
            console.log('传入的userId:', userId);
            console.log('userId类型:', typeof userId);
            
            try {
                loadUserDataCallCount++;
                console.log(`loadUserData第${loadUserDataCallCount}次被调用，用户ID:`, userId);
                
                // 添加更多详细的调试信息
                console.log('=== 详细调试信息 ===');
                console.log('当前URL:', window.location.href);
                console.log('浏览器环境检查:');
                console.log('  - fetch API是否可用:', typeof fetch === 'function');
                console.log('  - Promise是否可用:', typeof Promise === 'function');
                
                // 检查是否是预期的用户ID
                const urlArticleId = new URLSearchParams(window.location.search).get('id');
                if (userId != 9 && urlArticleId == 9) {
                    console.warn(`警告：正在加载用户ID ${userId}，但页面URL中的文章ID是 ${urlArticleId}`);
                }
                
                // 从localStorage获取JWT token
                const token = localStorage.getItem('token') || '';
                console.log('使用的认证令牌:', token);
                
                console.log('=== 即将发送fetch请求到 /user/api/detail ===');
                
                // 根据app/admin/controller/science/Science.php中的方法定义，正确调用方式
                const response = await fetch(`/user/api/detail?id=${userId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });
                const result = await response.json();
                
                // 添加调试日志
                console.log('用户详情API响应:', result);
                console.log('全局变量状态:', {
                    userInputGlobal: !!userInputGlobal,
                    userIdInputGlobal: !!userIdInputGlobal
                });
                
                // 适配API返回的状态码（可能是1或200）
                if ((result.code === 1 || result.code === 200) && result.data) {
                    // 如果有手机号，显示为"姓名 (手机号)"格式，否则只显示姓名
                    const displayText = result.data.phone 
                        ? `${result.data.name || '未知用户'} (${result.data.phone})`
                        : (result.data.name || '未知用户');
                    
                    // 使用全局变量设置用户昵称
                    if (userInputGlobal) {
                        userInputGlobal.value = displayText;
                        console.log('通过全局变量userInputGlobal回显用户昵称:', displayText);
                    } else {
                        // 尝试通过ID获取
                        const userNameInput = document.getElementById('user_name');
                        if (userNameInput) {
                            userNameInput.value = displayText;
                            console.log('通过ID获取输入框回显用户昵称:', displayText);
                        } else {
                            console.error('未找到用户输入框');
                        }
                    }
                } else {
                    console.warn('未找到用户数据或响应格式不正确');
                }
            } catch (error) {
                console.error('加载用户数据失败:', error);
            }
        }
        
        // 页面加载后直接调用loadUserData函数，用于调试
    console.log('=== 页面加载完成，准备直接调用loadUserData(9) ===');
    // loadUserData('9');
    
    // 为测试按钮添加点击事件监听器
    document.getElementById('testUserApiBtn').addEventListener('click', async function() {
        try {
            // 使用一个固定的用户ID进行测试，实际应用中可以改为从输入框获取
            const testUserId = 1; // 假设ID为1的用户存在
            
            console.log('测试用户详情API，用户ID:', testUserId);
            
            // 调用loadUserData函数测试API
            await loadUserData(testUserId);
            
            console.log('测试完成，用户数据已加载');
        } catch (error) {
            console.error('测试失败:', error);
            alert('测试失败: ' + error.message);
        }
    });
</script>
</body>

</html>